package SmartHome.View;

import SmartHome.Main;
import SmartHome.Session;
import SmartHome.dao.impl.*;
import SmartHome.entity.*;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
//import javafx.scene.chart.BarChart;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import SmartHome.util.JdbcUtil;
import SmartHome.util.DialogUtils;
import javafx.stage.Stage;
import SmartHome.util.BarChart;

import javax.swing.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class Controller {
    public StackPane outStackPane;
    public VBox loginBox;
    public TextField usernameField;
    public PasswordField passwordField;
    public CheckBox isSystemAdmin;
    public Button loginButton;
    public BorderPane UserPane;
    public BorderPane DevicePane;
    public BorderPane FamilyPane;
    public BorderPane TypePane;
    public Button typeAdd;
    public Button typeDelete;
    public Button typeUpdate;
    public Button typeSearch;
    public BorderPane searchPane;
    public Button famAdd;
    public Button famDelete;
    public Button famUpdate;
    public Button famSearch;
    public Button userAdd;
    public Button userDelete;
    public Button userUpdate;
    public Button userSearch;
    public Button divAdd;
    public Button divDelete;
    public Button divUpdate;
    public Button divSearch;
    public TextField famIdField;
    public TextField famTelField;
    public TextField famNameField;
    public Main MainApp;
    public TextField typeIDField;
    public TextField typeNameField;
    public TextField dNameField;
    public TextField dIDField;
    public TextField dTypeField;
    public TextField dDesField;
    public TextField dManField;
    public Label userNameLabel;
    public Label userManage;
    public Label familyManage;
    public Label deviceManage;
    public Label typeManage;
    public Label dataManage;
    public Label exit;
    public HBox filterBox;
    public ComboBox seMagazineClassBox;
    public Button filterButton;
    public HBox searchBox;
    public Label searchLabel;
    public ComboBox seCopiesNumBox;
    public Button searchButton;
    public TableView seTableView;
    public TextField uIDField;
    public TextField uTelField;
    public TextField uNameField;
    public HBox filterBoxc;
    public HBox searchBox3;
    public Label searchLabel3;
    public HBox filterBoxb;
    public BorderPane searchPaneb;
    public HBox searchBox2;
    public Label searchLabel2;
    public BorderPane searchPanec;
    public BorderPane searchPanea;
    public HBox filterBoxa;
    public HBox searchBox1;
    public Label searchLabel1;
    public TextField saFrom;
    public TextField saTo;
    public TextField saDev;
    public TextField saFam;
    public TextField saType;
    public TextField sbFrom;
    public TextField sbTo;
    public TextField sbDevice;
    public TextField sbTem;
    public TextField sbMin;
    public TextField sbMax;
    public TextField scFrom;
    public TextField scTo;
    public TextField scType;
    public TextField scDistribute;
    @FXML
    public TableView<FamilyInfo> famTableView;
    @FXML
    public TableColumn<FamilyInfo, Integer> familyId = new TableColumn<FamilyInfo, Integer>("Family ID");
    @FXML
    public TableColumn<FamilyInfo, String> familyName = new TableColumn<FamilyInfo, String>("Name");
    @FXML
    public TableColumn<FamilyInfo, Integer> fPhoneNumber = new TableColumn<FamilyInfo, Integer>("Tel");
    @FXML
    public TableView<UserInfo> userTableView;
    @FXML
    public TableColumn<UserInfo, Integer> userId = new TableColumn<UserInfo, Integer>("User ID");
    @FXML
    public TableColumn<UserInfo, String> userName = new TableColumn<UserInfo, String>("User Name");
    @FXML
    public TableColumn<UserInfo, String> UserPhoneNumber = new TableColumn<UserInfo, String>("Tel");
    @FXML
    public TableColumn<UserInfo, Integer> FId = new TableColumn<UserInfo, Integer>("Family Id");

    @FXML
    public TableView<DeviceInfo> deviceTableView;
    @FXML
    public TableColumn<DeviceInfo, Integer> deviceId = new TableColumn<DeviceInfo, Integer>("Device ID");
    @FXML
    public TableColumn<DeviceInfo, String> deviceName = new TableColumn<DeviceInfo, String>("Device Name");
    @FXML
    public TableColumn<DeviceInfo, String> deviceType = new TableColumn<DeviceInfo, String>("Device Type");
    @FXML
    public TableColumn<DeviceInfo, String> description = new TableColumn<DeviceInfo, String>("Description");
    @FXML
    public TableColumn<DeviceInfo, String> manufacturer = new TableColumn<DeviceInfo, String>("Manufacturer");
    @FXML
    public TableColumn<DeviceInfo, Integer> deviceTypeId = new TableColumn<DeviceInfo, Integer>("DeviceType ID");
    @FXML
    public TableColumn<DeviceInfo, Integer> familyID = new TableColumn<DeviceInfo, Integer>("Family ID");

    @FXML
    public TableView<DeviceTypeInfo> deviceTypeTableView;
    @FXML
    public TableColumn<DeviceTypeInfo, Integer> DeviceTypeId = new TableColumn<DeviceTypeInfo, Integer>("Type ID");
    @FXML
    public TableColumn<DeviceTypeInfo, String> DeviceTypeName = new TableColumn<DeviceTypeInfo, String>("Type Name");

    @FXML
    public TableView<RecordInfo> RecordTableView;
    @FXML
    public TableColumn<RecordInfo,Integer> recordId = new TableColumn<>("Record ID");
    @FXML
    public TableColumn<RecordInfo,String> recordTime = new TableColumn<>("Time");
    @FXML
    public TableColumn<RecordInfo,String> devicetype = new TableColumn<>("Type");
    @FXML
    public TableColumn<RecordInfo,Integer> Tempreture = new TableColumn<>("Temperature");
    @FXML
    public TableColumn<RecordInfo,Integer> Humidity = new TableColumn<>("Humidity");
    @FXML
    public TableColumn<RecordInfo,Integer> Brightness = new TableColumn<>("Brightness");
    @FXML
    public TableColumn<RecordInfo,Boolean> Open = new TableColumn<>("Open");

    public Button userSearch1;
    public TextField uFamField;
    public TextField dTypeIdField;
    public TextField dFamIdField;

    public void exitAction() {

    }

    //界面上方
    @FXML
    public void fAddAction() throws Exception {
        try {
            if (famIdField.getText().equals("") || famNameField.getText().equals("") || famTelField.getText().equals("")) {
                System.out.println("null");
                throw new NullPointerException("Please fill in all the information");
            } else {
                System.out.println("e");
                if (new FamilyDaoImpl().query1(Integer.parseInt(famIdField.getText())) != null) {
                    //存在但为0
                    if(new FamilyDaoImpl().query2() != null) {
                        System.out.println("h");
                        //更新
                        FamilyInfo familyInfo = new FamilyInfo(Integer.parseInt(famIdField.getText()),
                                famNameField.getText(), Integer.parseInt(famTelField.getText()), 1);
                        new FamilyDaoImpl().update(Integer.parseInt(famIdField.getText()), familyInfo);
                        initFamilyTable();
                        famIdField.setText("");
                        famTelField.setText("");
                        famNameField.setText("");
                    }
                    //存在，1
                    else {
                        System.out.println("exist");
                        throw new SQLException("The id already exists");
                    }
                }
                else {
                    FamilyInfo familyInfo = new FamilyInfo(Integer.parseInt(famIdField.getText()), famNameField.getText(), Integer.parseInt(famTelField.getText()), 1);
                    new FamilyDaoImpl().add(familyInfo);
                    initFamilyTable();
                    famIdField.setText("");
                    famTelField.setText("");
                    famNameField.setText("");
                }
            }
        } catch (NullPointerException e){
            System.out.println("1");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("Incomplete information");
            alert.showAndWait();
            famIdField.setText("");
            famTelField.setText("");
            famNameField.setText("");
        }
        catch (SQLException e){
            System.out.println("1");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("The id already exists");
            alert.showAndWait();
            famIdField.setText("");
            famTelField.setText("");
            famNameField.setText("");
        }
    }

    public void fDeleteAction() throws Exception {
        try {
            if(famIdField.getText().equals("")){
                System.out.println("null");
                throw new NullPointerException("Please fill in all the information");
            }
            else{
                System.out.println("e");
                if(new FamilyDaoImpl().query(Integer.parseInt(famIdField.getText())) != null){
                    System.out.println("exist");
                    int familyId = Integer.parseInt(famIdField.getText());
                    new FamilyDaoImpl().delete(familyId);
                    initFamilyTable();
                    famIdField.setText("");
                    famTelField.setText("");
                    famNameField.setText("");
                }
                else{
                    System.out.println("not exist");
                    throw new SQLException("The id do not exists");
                }
            }
        } catch (NullPointerException e){
            System.out.println("1");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("Incomplete ID information");
            alert.showAndWait();
            famIdField.setText("");
            famTelField.setText("");
            famNameField.setText("");
        }
        catch (SQLException e){
            System.out.println("1");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("The id do not exists");
            alert.showAndWait();
            famIdField.setText("");
            famTelField.setText("");
            famNameField.setText("");
        }
    }

    public void fSearchAction() throws Exception {
        try {
            if(famIdField.getText().equals("")){
                System.out.println("null");
                throw new NullPointerException("Please fill in the ID information");
            }
            else{
                System.out.println("e");
                if(new FamilyDaoImpl().query(Integer.parseInt(famIdField.getText())) != null){
                    System.out.println("exist");
                    List<FamilyInfo> thisFamily = new ArrayList<FamilyInfo>();
                    thisFamily.add(new FamilyDaoImpl().query(Integer.parseInt(famIdField.getText())));
                    familyId.setCellValueFactory(new PropertyValueFactory<>("familyId"));
                    familyName.setCellValueFactory(new PropertyValueFactory<>("familyName"));
                    fPhoneNumber.setCellValueFactory(new PropertyValueFactory<>("fPhoneNumber"));
                    famTableView.setItems(FXCollections.observableArrayList(thisFamily));
                    famIdField.setText("");
                    famTelField.setText("");
                    famNameField.setText("");
                }
                else{
                    throw new SQLException("The id don't exists");
                }
            }
        } catch (NullPointerException e){
            System.out.println("1");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("Incomplete ID information");
            alert.showAndWait();
            famIdField.setText("");
            famTelField.setText("");
            famNameField.setText("");
        }
        catch (SQLException e){
            System.out.println("1");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("The id do not exists");
            alert.showAndWait();
            famIdField.setText("");
            famTelField.setText("");
            famNameField.setText("");
        }
    }

    public void fUpdateAction() throws Exception {
        try {
            if (famIdField.getText().equals("")) {
                System.out.println("null");
                throw new NullPointerException("Please fill in ID information");
            } else {
                if (new FamilyDaoImpl().query(Integer.parseInt(famIdField.getText())) != null) {
                    System.out.println("exist");
                    FamilyInfo familyInfo = new FamilyInfo(Integer.parseInt(famIdField.getText()),
                            famNameField.getText(), Integer.parseInt(famTelField.getText()), 1);
                    new FamilyDaoImpl().update(Integer.parseInt(famIdField.getText()), familyInfo);
                    famIdField.setText("");
                    famTelField.setText("");
                    famNameField.setText("");
                } else {
                    throw new SQLException("The id don't exists");
                }
            }
        } catch (NullPointerException e) {
            System.out.println("1");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("Incomplete ID information");
            alert.showAndWait();
            famIdField.setText("");
            famTelField.setText("");
            famNameField.setText("");
        } catch (SQLException e) {
            System.out.println("1");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("The id do not exists");
            alert.showAndWait();
            famIdField.setText("");
            famTelField.setText("");
            famNameField.setText("");
        }
    }

        @FXML
    private void handleToFam() {
        DevicePane.setVisible(false);
        UserPane.setVisible(false);
        TypePane.setVisible(false);
        searchPane.setVisible(false);
        searchPanea.setVisible(false);
        searchPaneb.setVisible(false);
        searchPanec.setVisible(false);
        initFamilyTable();
        FamilyPane.setVisible(true);
    }

    @FXML
    public void initFamilyTable() {
        familyId.setCellValueFactory(new PropertyValueFactory<>("familyId"));
        familyName.setCellValueFactory(new PropertyValueFactory<>("familyName"));
        fPhoneNumber.setCellValueFactory(new PropertyValueFactory<>("fPhoneNumber"));
        famTableView.setItems(FXCollections.observableArrayList(new FamilyDaoImpl().getAll()));
    }

    public void uDeleteAction() {
        int userId = Integer.parseInt(uIDField.getText());
        new UserDaoImpl().delete(userId);
        initUserTable();
    }

    public void uAddAction() {
        try {
            if (uIDField.getText().equals("") || uNameField.getText().equals("") || uTelField.getText().equals("")) {
                System.out.println("null");
                throw new NullPointerException("Please fill in all the information");
            } else {
                System.out.println("e");
                if(new FamilyDaoImpl().query(Integer.parseInt(uFamField.getText()))==null){
                    throw new SQLException("The Family Id doesn't exist in FamilyInfo");
                }
                else if (new UserDaoImpl().query(Integer.parseInt(uIDField.getText())) != null) {
                    System.out.println("exist");
                    throw new SQLException("The id already exists");
                } else {
                    UserInfo userInfo = new UserInfo(Integer.parseInt(uIDField.getText()), uNameField.getText(), "e10adc3949ba59abbe56e057f20f883e", uTelField.getText(), Integer.parseInt(uFamField.getText()), 1);
                    new UserDaoImpl().add(userInfo);
                    initUserTable();
                }
            }
        } catch (Exception e) {
            System.out.println("1");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("The id already exists or Wrong information");
            alert.showAndWait();
            uIDField.setText("");
            uNameField.setText("");
            uTelField.setText("");
            uFamField.setText("");
        }
    }

    public void uUpdateAction() {
        UserInfo userInfo = new UserInfo(Integer.parseInt(uIDField.getText()), uNameField.getText(), "e10adc3949ba59abbe56e057f20f883e", uTelField.getText(), Integer.parseInt(uFamField.getText()), 1);
        new UserDaoImpl().update(Integer.parseInt(uIDField.getText()), userInfo);
        initUserTable();
    }

    public void uSearchAction() {
        List<UserInfo> thisUser = new ArrayList<UserInfo>();
        thisUser.add(new UserDaoImpl().query(Integer.parseInt(uIDField.getText())));
        userId.setCellValueFactory(new PropertyValueFactory<>("userId"));
        userName.setCellValueFactory(new PropertyValueFactory<>("userName"));
        UserPhoneNumber.setCellValueFactory(new PropertyValueFactory<>("UserPhoneNumber"));
        userTableView.setItems(FXCollections.observableArrayList(thisUser));
    }

    @FXML
    private void handleToUser() {
        DevicePane.setVisible(false);
        FamilyPane.setVisible(false);
        TypePane.setVisible(false);
        searchPane.setVisible(false);
        searchPanea.setVisible(false);
        searchPaneb.setVisible(false);
        searchPanec.setVisible(false);
        initUserTable();
        UserPane.setVisible(true);
    }

    @FXML
    public void initUserTable() {
        userId.setCellValueFactory(new PropertyValueFactory<>("userId"));
        userName.setCellValueFactory(new PropertyValueFactory<>("userName"));
        UserPhoneNumber.setCellValueFactory(new PropertyValueFactory<>("UserPhoneNumber"));
        FId.setCellValueFactory(new PropertyValueFactory<>("FId"));
        userTableView.setItems(FXCollections.observableArrayList(new UserDaoImpl().getAll()));
    }

    public void dAddAction() throws Exception{
        try {
            if (dIDField.getText().equals("") || dNameField.getText().equals("") ||
                    dTypeField.getText().equals("") || dDesField.getText().equals("") ||
                    dManField.getText().equals("")) {
                throw new NullPointerException("Please fill in all the information");
            } else {
                if(new DeviceTypeImpl().query(Integer.parseInt(dIDField.getText()))==null||
                new FamilyDaoImpl().query(Integer.parseInt(dIDField.getText()))==null){
                    throw new SQLException("foreign key constraints!");
                }
                else if (new DeviceDaoImpl().query(Integer.parseInt(dIDField.getText())) != null) {
                    throw new SQLException("The id already exists");
                } else {
                    DeviceInfo deviceInfo = new DeviceInfo(Integer.parseInt(dIDField.getText()), 
                            dNameField.getText(), dTypeField.getText(), 
                            dDesField.getText(), dManField.getText(),Integer.parseInt(dTypeIdField.getText()),
                            Integer.parseInt(dFamIdField.getText()), Boolean.TRUE);
                    new DeviceDaoImpl().add(deviceInfo);
                    initDeviceTable();
                }
            }
        } catch (Exception e) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("The id already exists or Wrong information");
            alert.showAndWait();
            dIDField.setText("");
            dNameField.setText("");
            dTypeField.setText("");
            dTypeIdField.setText("");
            dFamIdField.setText("");
            dDesField.setText("");
            dManField.setText("");

        }
    }


    public void dDeleteAction() {
        int deviceId = Integer.parseInt(dIDField.getText());
        new DeviceDaoImpl().delete(deviceId);
        initDeviceTable();
    }


    public void dSearchAction() {
        List<DeviceInfo> thisDevice = new ArrayList<DeviceInfo>();
        thisDevice.add(new DeviceDaoImpl().query(Integer.parseInt(dIDField.getText())));
        deviceId.setCellValueFactory(new PropertyValueFactory<>("deviceId"));
        deviceName.setCellValueFactory(new PropertyValueFactory<>("deviceName"));
        deviceType.setCellValueFactory(new PropertyValueFactory<>("deviceType"));
        description.setCellValueFactory(new PropertyValueFactory<>("deviceDescription"));
        manufacturer.setCellValueFactory(new PropertyValueFactory<>("deviceVendor"));
    }

    public void dUpdateAction() {
        DeviceInfo deviceInfo = new DeviceInfo(Integer.parseInt(dIDField.getText()),
                dNameField.getText(), dTypeField.getText(),
                dDesField.getText(), dManField.getText(),Integer.parseInt(dTypeIdField.getText()),
                Integer.parseInt(dFamIdField.getText()), Boolean.TRUE);
        new DeviceDaoImpl().update(Integer.parseInt(dIDField.getText()), deviceInfo);
        initDeviceTable();
    }

    @FXML
    private void handleToDevice() {
        UserPane.setVisible(false);
        FamilyPane.setVisible(false);
        TypePane.setVisible(false);
        searchPane.setVisible(false);
        searchPanea.setVisible(false);
        searchPaneb.setVisible(false);
        searchPanec.setVisible(false);
        initDeviceTable();
        DevicePane.setVisible(true);
    }

    @FXML
    public void initDeviceTable() {
        deviceId.setCellValueFactory(new PropertyValueFactory<>("deviceId"));
        deviceName.setCellValueFactory(new PropertyValueFactory<>("deviceName"));
        deviceType.setCellValueFactory(new PropertyValueFactory<>("deviceType"));
        description.setCellValueFactory(new PropertyValueFactory<>("description"));
        manufacturer.setCellValueFactory(new PropertyValueFactory<>("manufacturer"));
        deviceTypeId.setCellValueFactory(new PropertyValueFactory<>("deviceTypeId"));
        familyID.setCellValueFactory(new PropertyValueFactory<>("familyID"));
        deviceTableView.setItems(FXCollections.observableArrayList(new DeviceDaoImpl().getAll()));
    }

    @FXML
    public void initTypeTable() {
        DeviceTypeId.setCellValueFactory(new PropertyValueFactory<>("DevicesTypeId"));
        DeviceTypeName.setCellValueFactory(new PropertyValueFactory<>("DevicesTypeName"));
        deviceTypeTableView.setItems(FXCollections.observableArrayList(new DeviceTypeImpl().getAll()));
    }

    @FXML
    private void handleToType() {
        UserPane.setVisible(false);
        FamilyPane.setVisible(false);
        DevicePane.setVisible(false);
        searchPane.setVisible(false);
        searchPanea.setVisible(false);
        searchPaneb.setVisible(false);
        searchPanec.setVisible(false);
        initTypeTable();
        TypePane.setVisible(true);
    }

    @FXML
    public void handleToData() {
        UserPane.setVisible(false);
        FamilyPane.setVisible(false);
        DevicePane.setVisible(false);
        TypePane.setVisible(false);
        searchPanea.setVisible(false);
        searchPaneb.setVisible(false);
        searchPanec.setVisible(false);
        initTypeTable();
        searchPane.setVisible(true);
    }

    public void sStatistics(ActionEvent actionEvent) {
        UserPane.setVisible(false);
        FamilyPane.setVisible(false);
        DevicePane.setVisible(false);
        TypePane.setVisible(false);
        searchPanea.setVisible(false);
        searchPane.setVisible(false);
        searchPanec.setVisible(false);
        initTypeTable();
        searchPaneb.setVisible(true);
    }

    public void sDistribute(ActionEvent actionEvent) {
        UserPane.setVisible(false);
        FamilyPane.setVisible(false);
        DevicePane.setVisible(false);
        TypePane.setVisible(false);
        searchPanea.setVisible(false);
        searchPaneb.setVisible(false);
        searchPane.setVisible(false);
        initTypeTable();
        searchPanec.setVisible(true);
    }


    @FXML
    public void sSearch(ActionEvent actionEvent) {
        UserPane.setVisible(false);
        FamilyPane.setVisible(false);
        DevicePane.setVisible(false);
        TypePane.setVisible(false);
        searchPane.setVisible(false);
        searchPaneb.setVisible(false);
        searchPanec.setVisible(false);
        initRecordTable();
        searchPanea.setVisible(true);
    }
    @FXML
    public void initRecordTable(){
        recordId.setCellValueFactory(new PropertyValueFactory<>("recordId"));
        recordTime.setCellValueFactory(new PropertyValueFactory<>("recordTime"));
        devicetype.setCellValueFactory(new PropertyValueFactory<>("devicetype"));
        Tempreture.setCellValueFactory(new PropertyValueFactory<>("Temperature"));
        Humidity.setCellValueFactory(new PropertyValueFactory<>("Humidity"));
        Brightness.setCellValueFactory(new PropertyValueFactory<>("Brightness"));
        Open.setCellValueFactory(new PropertyValueFactory<>("Open"));
        RecordTableView.setItems(FXCollections.observableArrayList(new RecordDaoImpl().getAll()));
    }
    public void tAddAction() {
        try {
            if (typeIDField.getText().equals("") || typeNameField.getText().equals("")) {
                System.out.println("null");
                throw new NullPointerException("Please fill in all the information");
            } else {
                System.out.println("e");
                if (new DeviceTypeImpl().query(Integer.parseInt(typeIDField.getText())) != null) {
                    System.out.println("exist");
                    throw new SQLException("The id already exists");
                } else {
                    DeviceTypeInfo deviceTypeInfo = new DeviceTypeInfo(Integer.parseInt(typeIDField.getText()),typeNameField.getText(),1);
                    new DeviceTypeImpl().add(deviceTypeInfo);
                    initTypeTable();
                }
            }
        } catch (Exception e) {
            System.out.println("1");
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Oops!");
            alert.setHeaderText("There is an error in your information");
            alert.setContentText("The id already exists or Incomplete information");
            alert.showAndWait();
        }
    }

    public void tDeleteAction() {
        int deviceTypeId = Integer.parseInt(typeIDField.getText());
        new DeviceTypeImpl().delete(deviceTypeId);
        initTypeTable();
    }

    public void tSearchAction() {
        List<DeviceTypeInfo> thisDeviceType = new ArrayList<DeviceTypeInfo>();
        thisDeviceType.add(new DeviceTypeImpl().query(Integer.parseInt(typeIDField.getText())));
        DeviceTypeId.setCellValueFactory(new PropertyValueFactory<>("DevicesTypeId"));
        DeviceTypeName.setCellValueFactory(new PropertyValueFactory<>("DevicesTypeName"));
        deviceTypeTableView.setItems(FXCollections.observableArrayList(thisDeviceType));
    }

    public void tUpdateAction() {
        DeviceTypeInfo deviceTypeInfo = new DeviceTypeInfo(Integer.parseInt(typeIDField.getText()),typeNameField.getText(),1);
        new DeviceTypeImpl().update(Integer.parseInt(typeIDField.getText()),deviceTypeInfo);
        initTypeTable();
    }

    public Main getMainApp() {
        return MainApp;
    }

    public void setMainApp(Main MainApp) {
        this.MainApp = MainApp;
    }

    @FXML
    public void handleLogin() throws Exception {
        Connection conn = null;
        String sql = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        if (isSystemAdmin.isSelected()) {
            sql = "select * from `Administrators` where AdminId = ? and AdminPassword = ? and AdminType =1";
            Session.setId(Integer.parseInt(usernameField.getText()));
            System.out.println(Session.getId());
        } else {
            sql = "select * from `Administrators` where AdminId = ? and AdminPassword = ? and AdminType =0";

            Session.setId(Integer.parseInt(usernameField.getText()));
            System.out.println(Session.getId());
        }
        try {
            conn = JdbcUtil.getConn();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(usernameField.getText()));
            ps.setInt(2, Integer.parseInt(passwordField.getText()));
            rs = ps.executeQuery();
            if (rs.next()) {
                Stage stage = new Stage();
                if (isSystemAdmin.isSelected()) {
                    Parent root = FXMLLoader.load(getClass().getResource("Admin.fxml"));
                    Scene scene = new Scene(root);
                    stage.setScene(scene);
                    stage.show();
                } else {
                    Parent root = FXMLLoader.load(getClass().getResource("vendor.fxml"));
                    Scene scene = new Scene(root);
                    stage.setScene(scene);
                    stage.show();
                }
                MainApp.getPrimaryStage().close();
            } else {
                throw new NullPointerException("Wrong Information! Try Again!");
            }
        } catch (Exception e) {
            DialogUtils.tips(MainApp.getPrimaryStage(), "Your id and password are not match" +
                    "or your imformation is not implement. ");
            usernameField.setText("");
            passwordField.setText("");
            usernameField.requestFocus();
        } finally {
            JdbcUtil.close(conn, ps, rs);
        }

    }

    public void dataManageAction(MouseEvent mouseEvent) {
    }

    public void aFilter(ActionEvent actionEvent) {
    }

    public void aSearchd(ActionEvent actionEvent) {
        List<RecordInfo> thisRecord = new ArrayList<RecordInfo>();
        thisRecord.add(new RecordDaoImpl().querydevice(Integer.parseInt(saDev.getText())));
        recordId.setCellValueFactory(new PropertyValueFactory<>("recordId"));
        recordTime.setCellValueFactory(new PropertyValueFactory<>("recordTime"));
        devicetype.setCellValueFactory(new PropertyValueFactory<>("devicetype"));
        Tempreture.setCellValueFactory(new PropertyValueFactory<>("Tempreture"));
        Humidity.setCellValueFactory(new PropertyValueFactory<>("Humidity"));
        Brightness.setCellValueFactory(new PropertyValueFactory<>("Brightness"));
        Open.setCellValueFactory(new PropertyValueFactory<>("Open"));
        RecordTableView.setItems(FXCollections.observableArrayList(thisRecord));
    }

    public void aSearchf(ActionEvent actionEvent) {
    }

    public void aSearcht(ActionEvent actionEvent) {
    }

    public void bFilter(ActionEvent actionEvent) {
    }

    public void bSearch(ActionEvent actionEvent) {
        System.out.println("jkkkkkkkkkkkkkkkkkkkkkkkkkkj" );
        int id = Integer.parseInt(sbDevice.getText());
        String valueType = sbTem.getText();
        int min = Integer.parseInt(sbMin.getText());
        int max = Integer.parseInt(sbMax.getText());
//        String[] from=sbFrom.getText().split(":");
//        String[] to=sbTo.getText().split(":");
        int[] count1 = new int[max-min+1];
        for (int i=min;i<=max;i++)
        {
            count1[i-min] = new RecordDaoImpl().count(i);
            System.out.println(count1[i-min]);
        }

        String[] tem = new String[max-min+1];
        for (int j=min;j<=max;j++)
        {
            tem[j-min] = String.valueOf(tem);
            System.out.println(tem[j-min]);
        }
        System.out.println("jjjjjjjjjjj" );
        JFrame frame=new JFrame("Static");
//        frame.setLayout(new GridLayout(2,2,10,10));
        frame.add(new BarChart("Temperature Statics","Temperature","Number", count1,tem).getChartPanel());           //添加柱形图
        //frame.add(new BarChart1().getChartPanel());          //添加柱形图的另一种效果
//        frame.add(new com.njue.testJFreeChart.PieChart().getChartPanel());           //添加饼状图
//        frame.add(new TimeSeriesChart().getChartPanel());    //添加折线图
        frame.setBounds(50, 50, 800, 600);
        frame.setVisible(true);
    }

    public void cFilter(ActionEvent actionEvent) {
    }

    public void cSearch(ActionEvent actionEvent) {
    }
}
